Fetch Function
Description
fetchFunction
is a utility function designed to simplify making HTTP requests within a JavaScript application. It allows you to specify a URL and request options, and handles the fetch operation with built-in support for request and response interception. It's defined inside api.js file present in your directory.
Parameters:
url: A string representing the endpoint URL to which the request will be made.
options: An object containing various options for the request, such as method, headers, body, etc.
Return Value:
A Promise that resolves with the parsed JSON response from the server.
Example Usage:
const fetchFunction = (url, options) => {
let baseURL = process.env.API_URL
let finalUrl = baseURL + url
// Request Interceptor - modify request here
return fetch(finalUrl, options)
.then(response => {
return response.json().then(parsedResponse => {
// Response Interceptor - modify response here
console.log("parsedResponse", parsedResponse)
return parsedResponse
})
})
}
export default fetchFunction
Interceptors:
Request Interceptor: You can modify the request before it is sent to the server by updating the
options
object. For example, you can add custom headers, authentication tokens, etc.Response Interceptor: You can modify the response received from the server before it's returned to the calling code. This can be useful for handling errors, logging, or transforming the response data.
Example Request Interceptor (Uncomment and Customize as Needed):
// Request Interceptor
options.headers.Authorization = 'Bearer your_token';
Example Response Interceptor (Uncomment and Customize as Needed):
// Response Interceptor
if (parsedResponse.error) {
throw new Error(parsedResponse.error.message);
}
Note:
This function relies on the global
fetch
function, which is commonly available in modern browsers and can be polyfilled for compatibility with older browsers.Make sure to set the
process.env.API_URL
variable to the base URL of your API before using this function.